/**
 * Copyright (C) 2009 Matteo Merli <mm@merlimat.org>
 * 
 * $Id: PxlFunction.java 24 2009-01-19 19:49:05Z matteo.merli $
 * $URL: http://pxl-lang.googlecode.com/svn/trunk/src/main/java/pxl/types/PxlFunction.java $
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *         http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package pxl.types;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.antlr.runtime.tree.CommonTree;
import org.antlr.runtime.tree.CommonTreeNodeStream;
import org.antlr.runtime.tree.TreeNodeStream;

import pxl.Context;
import pxl.Scope;
import pxl.errors.ArithmeticError;
import pxl.errors.PxlException;
import pxl.errors.ReturnException;
import pxl.errors.StackError;
import pxl.grammar.classes.PxlTreeWalker;
import pxl.types.annotations.Exported;
import pxl.types.util.FunctionCall;
import pxl.types.util.PxlArgument;
import pxl.types.util.PxlParametersList;

public class PxlFunction extends PxlObject
{

    /** Function name */
    private final String name;

    /** Argument names list */
    private final PxlParametersList parameters;

    /** Abstract tree of block of code that composes the function. */
    private final CommonTree codeBlock;

    private final Scope enclosingScope;

    private final boolean isLambda;

    public PxlFunction( String name, PxlParametersList parameters,
            CommonTree codeBlock, Scope enclosingScope, boolean isLambda )
    {
        this.name = name;
        this.parameters = parameters;
        this.codeBlock = codeBlock;
        this.enclosingScope = enclosingScope;
        this.isLambda = isLambda;
    }

    @Override
    public String getType()
    {
        return "function";
    }

    @Exported
    @Override
    public PxlString __repr__()
    {
        // <type name @ addr>
        return new PxlString( String.format( "<%s %s @ %u>", getType(), name,
                hashCode() ) );
    }

    // Operators

    /**
     * 
     */
    @Exported
    @Override
    public PxlObject __call__( List<PxlArgument> args )
    {
        Object[] values = FunctionCall.getArgumentValues( name, parameters,
                args );

        // Create a new Scope and push function parameters
        Scope scope = new Scope( name, enclosingScope );
        Context.getInstance().push( scope );
        for ( int i = 0; i < values.length; i++ )
            scope.put( parameters.get( i ).name(), (PxlObject) values[i] );

        TreeNodeStream stream = new CommonTreeNodeStream( codeBlock );
        PxlTreeWalker treeWalker = new PxlTreeWalker( stream );
        PxlObject res = None.instance();

        try
        {
            // Executes the function code block
            if ( isLambda )
                res = treeWalker.expr();
            else
                treeWalker.stmtlist();
        }
        catch ( ReturnException ret )
        {
            // the function returned a value
            res = ret.getResult();
        }
        catch ( PxlException pe )
        {
            Context.getInstance().saveCurrentScope();
            throw pe;
        }
        catch ( StackOverflowError soe )
        {
            Context.getInstance().saveCurrentScope();
            throw new StackError();
        }
        catch ( ArithmeticException ae )
        {
            Context.getInstance().saveCurrentScope();
            throw new ArithmeticError( ae );
        }
        catch ( Throwable t )
        {
            throw new RuntimeException( t );
        }
        finally
        {
            // Clear the function context
            Context.getInstance().pop();
        }

        return res;
    }

    // Attributes

    private static final Map<String, PxlObject> attrs = PxlObject
            .getExportedMethods( PxlFunction.class );

    @Override
    protected PxlObject getAttribute( String name )
    {
        return attrs.get( name );
    }

    @Override
    protected Collection<String> getAttributeNames()
    {
        return attrs.keySet();
    }

}
